package cn.suzhang.jsharp.module.sys.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.suzhang.jsharp.common.dao.BaseDao;
import cn.suzhang.jsharp.common.service.BaseService;
import cn.suzhang.jsharp.module.sys.dao.ResourceDao;
import cn.suzhang.jsharp.module.sys.entity.SysResource;
import cn.suzhang.jsharp.module.sys.entity.SysRole;
import cn.suzhang.jsharp.module.sys.vo.ZtreeView;

@Service
public class ResourceService extends BaseService<SysResource, Long> {

	@Autowired
	private ResourceDao resourceDao;
	
	@Autowired
	private RoleService roleService;

	@Override
	public BaseDao<SysResource, Long> getBaseDao() {
		return resourceDao;
	}

	public void saveOrUpdate(SysResource resource) {
		if (resource.getId() != null) {
			SysResource dbResource = find(resource.getId());
			dbResource.setSourceName(resource.getSourceName());
			dbResource.setSourceKey(resource.getSourceKey());
			dbResource.setType(resource.getType());
			dbResource.setSourceUrl(resource.getSourceUrl());
			dbResource.setLevel(resource.getLevel());
			dbResource.setSort(resource.getSort());
			dbResource.setParent(resource.getParent());
			update(dbResource);
		} else {
			save(resource);
		}
	}
	
	public List<ZtreeView> tree(Long roleId) {
		List<ZtreeView> resulTreeNodes = new ArrayList<ZtreeView>();
		SysRole role = roleService.find(roleId);
		Set<SysResource> roleResources = role.getResources();
		resulTreeNodes.add(new ZtreeView(0L, null, "系统菜单", true));
		ZtreeView node;
		List<SysResource> all = resourceDao.findAll();
		for (SysResource resource : all) {
			node = new ZtreeView();
			node.setId(Long.valueOf(resource.getId()));
			if (resource.getParent() == null) {
				node.setpId(0L);
			} else {
				node.setpId(Long.valueOf(resource.getParent().getId()));
			}
			node.setName(resource.getSourceName());
			if (roleResources != null && roleResources.contains(resource)) {
				node.setChecked(true);
			}
			resulTreeNodes.add(node);
		}
		return resulTreeNodes;
	}

}
